// 打印之前
import Vue from 'vue'
import { printExpress, printPickOrder } from '@/api/outStorage'
import PrintWaybill from '@/components/Printing/printWaybill.js'
import { getQueryString } from '@/utils/index'
import { MessageBox } from 'element-ui'

export default function handlePrint(url) {
  const type = getQueryString('type', url)
  const listInterface = getQueryString('listInterface', url)
  let printCode = localStorage.getItem('printCode')
  const printData = localStorage.getItem('printData')
  if (!type && !listInterface && printData) {
    // 普通复核、爆品复核 打印
    // console.log(printData)
    const formatPrintData = JSON.parse(printData)

    const printed = []
    formatPrintData.forEach(item => {
      if (item.waybillPrintCount > 0) printed.push(item.code)
    })

    if (printed.length > 0) {
      const msgTip = `您选择的单据中有${printed.length}条已经打印过，请确认是否继续？`
      MessageBox.confirm(msgTip, '提示', {
        type: 'warning'
      }).then(() => {
        startPrint2(formatPrintData)
      }).catch(() => {})
    } else {
      startPrint2(formatPrintData)
    }
    return
  }
  if (!printCode) {
    this.$message.error('打印数据获取失败，请关闭页面重试！')
    return
  }
  if (type !== 'string') printCode = JSON.parse(printCode)
  const rLoading = Vue.prototype.openLoading({
    text: '打印数据获取中，请勿动！...',
    duration: 'n'
  })
  const requestOperation = {
    'printExpress': printExpress,
    'printPickOrder': printPickOrder
  }
  requestOperation[listInterface](printCode).then(res => {
    if (res.status === 0 && res.data.length > 0) {
      localStorage.removeItem('printCode')
      const printed = []
      res.data.forEach(item => {
        if (item.waybillPrintCount > 0) printed.push(item.code)
      })
      // dangerouslyUseHTMLString: true
      // const msgTip = `<div>您选择的单据中有<strong style="color: red; font-size: 16px; margin: 0 4px;">${printed.length}</strong>条已经打印过</div><div>请确认是否继续？</div>`
      if (printed.length > 0) {
        const msgTip = `您选择的单据中有${printed.length}条已经打印过，请确认是否继续？`
        MessageBox.confirm(msgTip, '提示', {
          type: 'warning'
        }).then(() => {
          startPrint(res.data, listInterface)
        }).catch(() => {})
      } else {
        startPrint(res.data, listInterface)
      }
    }
  }).finally(() => rLoading.close())
}

function startPrint(printData, printType) {
  new PrintWaybill({ printData, printType }, () => {
    Vue.prototype.$eventBus.$emit('refreshList')
  }).initSocket()
}

const printQueue = [] // 待打印的数据
let currentTaskId = '' // 当前打印的数据标识
function startPrint2(printData) {
  const printObj = {
    id: Date.now(),
    data: printData
  }
  printQueue.push(printObj)
  if (currentTaskId === '') reviewPrint()
}
function reviewPrint() {
  console.log(printQueue.length, '<-----任务数 *任务队列* 数据------>', printQueue)
  // 普通复核、爆品复核 打印
  if (printQueue.length > 0) {
    currentTaskId = printQueue[0].id
    new PrintWaybill({ printData: printQueue[0].data }, (res) => {
      printQueue.forEach((item, idx, arr) => {
        if (item.id === currentTaskId) arr.splice(idx, 1)
      })
      if (printQueue.length > 0) {
        reviewPrint()
      } else {
        currentTaskId = ''
        localStorage.removeItem('printData')
        const str = Math.random().toString(36).substr(2, 10)
        Vue.prototype.$eventBus.$emit('printFinish') // 拣货单管理，波次打印完通知（清空输入框波次号）
        Vue.prototype.$eventBus.$emit('refreshCurrentPage') // 普通复核，复核完成 && 打印完成 后刷新当前页
        localStorage.setItem(`printComplete${str}`, JSON.stringify(res))
      }
    }).initSocket()
  }
}
